package com.zwps.biz.domain.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zwps.biz.api.model.dto.strsvrr.StRsvrRDTO;
import com.zwps.biz.api.model.vo.pubpointall.PubPointAllVO;
import com.zwps.biz.api.model.vo.pubpointall.PubSectionWarnVO;
import com.zwps.biz.api.model.vo.strsvrr.*;
import com.zwps.biz.api.model.vo.ststbprp.StStbprpBVO;
import com.zwps.biz.dal.db.dao.PubPointAllDAO;
import com.zwps.biz.dal.db.dao.StPptnRDAO;
import com.zwps.biz.dal.db.dao.StStbprpBDAO;
import com.zwps.biz.dal.db.object.PubPointAllDO;
import com.zwps.biz.dal.db.object.RealTimeHeatingDO;
import com.zwps.biz.dal.db.object.StStbprpBDO;
import com.zwps.biz.domain.converter.StStbprpBConverter;
import com.zwps.biz.domain.converter.StrSvrRConverter;
import com.zwps.common.core.exception.UserActionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwps.biz.dal.db.object.StRsvrRDO;
import com.zwps.biz.dal.db.dao.StRsvrRDAO;
import com.zwps.biz.domain.service.StRsvrRService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class StRsvrRServiceImpl extends ServiceImpl<StRsvrRDAO, StRsvrRDO> implements StRsvrRService {
    @Autowired
    private StRsvrRDAO stRsvrRDAO;
    @Autowired
    private StStbprpBDAO stbprpBDAO;
    @Autowired
    private StPptnRDAO stPptnRDAO;
    @Autowired
    private PubPointAllDAO pubPointAllDAO;

    @Override
    public List<StRsvrRVO> getStrSvrR(StRsvrRDTO ids) {
        if (null!=ids.getMode() && "1".equals(ids.getMode())) {
            ids.setStcd("库水位");
        }
        QueryWrapper<StRsvrRDO> wrapper = new QueryWrapper<>();
        wrapper.eq("sr.STCD", ids.getStcd());
        if (ids.getStartTime() != null) {
            wrapper.ge("TM", ids.getStartTime());
        }

        if (ids.getEndTime() != null) {
            wrapper.le("TM", ids.getEndTime());
        }
        ids.setMode("0".equals(ids.getMode()) ? "" : "1".equals(ids.getMode()) ? "_manual" : ids.getMode());
        if (null!=ids.getShowTime()){
            switch (ids.getShowTime()) {
                case "1":
                    wrapper.apply("MINUTE(TM) = 0")
                            .apply("SECOND(TM) = 0");
                    break;
                case "2":
                    wrapper.apply("HOUR(TM) IN ( 8)")
                            .apply("MINUTE(TM) = 0")
                            .apply("SECOND(TM) = 0");
                    break;

            }
        }
        wrapper.orderByDesc("TM");
        String mode = ids.getMode();

        List<StRsvrRVO> strList = stRsvrRDAO.queryList(wrapper, mode);
        return strList;
    }

    @Override
    public GetLastStRsvrRVO getLastStRsvrR(String stcd) {
        List<PubSectionWarnVO> lists = pubPointAllDAO.geDrpByType();
        double average = lists.stream()
                .mapToDouble(item ->Double.valueOf(item.getVals().toString()))
                .average()
                .orElse(0.0);
        GetLastStRsvrRVO lastStRsvrRManual = stRsvrRDAO.getLastStRsvrR(stcd);
       lastStRsvrRManual.setDrp(BigDecimal.valueOf(average).setScale(2, RoundingMode.HALF_UP));
        Date tm = lastStRsvrRManual.getTm();

        if (null == lastStRsvrRManual) {
            return new GetLastStRsvrRVO();
        }
        // 检查降雨量是否为 null 或者小于等于 0，如果是则设置为 0
        if (null == lastStRsvrRManual.getDrp()) {
            lastStRsvrRManual.setDrp(BigDecimal.valueOf(0));
        }
        List<String> list = Arrays.asList("62901301", "62901303", "62901304");
        for (String s : list) {
            QueryWrapper<StRsvrRDO> wrapper = new QueryWrapper<>();
            wrapper.eq("STCD", s)
                    .orderByDesc("TM")
                    .last("LIMIT 1");
            // 执行查询
            StRsvrRDO stRsvrRDO= stRsvrRDAO.selectOne(wrapper);
            if (stRsvrRDO.getStcd().equals("62901301")){
                lastStRsvrRManual.setStcd_62901301(stRsvrRDO.getRz());
            }
            if (stRsvrRDO.getStcd().equals("62901303")){
                lastStRsvrRManual.setStcd_62901303(stRsvrRDO.getRz());
            }
            if (stRsvrRDO.getStcd().equals("62901304")){
                lastStRsvrRManual.setStcd_62901304(stRsvrRDO.getRz());
            }

        }
        BigDecimal w=stRsvrRDAO.getLastW();
        if ( lastStRsvrRManual.getW()==null){
            lastStRsvrRManual.setW(w);
        }
        return lastStRsvrRManual;
    }

    @Override
    public List<String> getStcd() {
        QueryWrapper<StRsvrRDO> wrapper = new QueryWrapper<>();
        wrapper.select("STCD");
        List<StRsvrRDO> stRsvrRDOS = stRsvrRDAO.selectList(wrapper);
        List<String> stcdList = stRsvrRDOS.stream()
                .map(StRsvrRDO::getStcd)
                .distinct()
                .collect(Collectors.toList());
        return stcdList;
    }

    @Override
    public List<StRsvrInitVO> getInitStrSvrR(String stcd) {
        if (stcd == null) {
            stcd = "62901300";
        }
//        List<StRsvrRDO> stRsvrRDOS = stRsvrRDAO.selectList(
//                new QueryWrapper<StRsvrRDO>().eq("STCD", stcd)
//                        .apply("HOUR(TM) IN ( 8)")
//                        .apply("MINUTE(TM) = 0")
//                        .apply("SECOND(TM) = 0")
//                        .orderByDesc("TM")
//                        .last("LIMIT 7"));
//        ArrayList<StRsvrInitVO> list = new ArrayList<>();
//        if (CollectionUtil.isNotEmpty(stRsvrRDOS)) {
//            for (StRsvrRDO stRsvrRBDO : stRsvrRDOS) {
//                StRsvrInitVO stbprpBVO = StrSvrRConverter.INSTANCE.toStRsvrInitVO(stRsvrRBDO);
//                list.add(stbprpBVO);
//            }
//        }
        return stRsvrRDAO.getInitStrSvrR(stcd);
    }

    @Override
    public List<GetLastValueVO> getLatestValue() {
        List<StStbprpBDO> pp = stbprpBDAO.selectStcd("pp");
        List<String> list=new ArrayList<>();
        for (StStbprpBDO stStbprpBDO : pp) {
            list.add(stStbprpBDO.getStcd());
        }

        return stRsvrRDAO.getLatestValue(list);
    }

    @Override
    public List<GetLastValueVO> getExLatestValue() {
        String[] pp = { "10004" }, rs = { "10001", "10002", "10003", "10005" };

        List<GetLastValueVO> ppLastValues = stRsvrRDAO.getExPptnLatestValue(new ArrayList<String>(Arrays.asList(pp)));
        List<GetLastValueVO> rsLastValues = stRsvrRDAO.getExRsvrLatestValue(new ArrayList<String>(Arrays.asList(rs)));

        return Stream.concat(ppLastValues.stream(), rsLastValues.stream())
                .collect(Collectors.toList());
    }

    @Override
    public List<GetLastValueVO> getWarterLatestValue() {
        List<StStbprpBDO> pp = stbprpBDAO.selectStcd("rr");
        List<String> list=new ArrayList<>();
        for (StStbprpBDO stStbprpBDO : pp) {
            list.add(stStbprpBDO.getStcd());
        }
        return stRsvrRDAO.getWarterLatestValue(list);
    }

    @Override
    public List<GetLastValueVO> getHistoryValue(String stcd, Integer type, String startTime, String endTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        if (startTime == null && endTime == null) {
            LocalDateTime now = LocalDateTime.now();
            endTime = now.format(formatter);
            startTime = now.minus(1, ChronoUnit.MONTHS).format(formatter);
        } else if (startTime == null) {
            // 如果只有 startTime 为 null，基于 endTime 计算 startTime
            LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);
            startTime = endDateTime.minus(1, ChronoUnit.MONTHS).format(formatter);
        } else if (endTime == null) {
            // 如果只有 endTime 为 null，设置为当前时间
            endTime = LocalDateTime.now().format(formatter);
        }

        return stPptnRDAO.getHistoryValue(stcd, type, startTime, endTime);
    }
}
